<template>
  <div v-loading="loading">
    <div class="header-div">
      <div class="delete-btn-div">
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="deleteSelection"
        >删除</el-button>
      </div>
      <div class="buy-div">
        <div class="choose">
          <span>已选商品{{ buyCount }}件</span>
        </div>
        <div class="total-money">
          <span>合计￥{{ totalMoney | num2Point }}</span>
        </div>
        <div class="buy-btn">
          <el-button
            type="success"
            icon="el-icon-sold-out"
            @click="buyGoodList"
          >结算</el-button>
        </div>
      </div>
    </div>
    <div class="table-div">
      <el-table
        :data="userCart"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column label="商品信息" width="350">
          <template slot-scope="scope">
            <div class="book-img-des-container">
              <div class="book-img">
                <el-image
                  style="width: 100%; height: 100%"
                  :src="scope.row.book.bookImgs[0].imgName"
                  fit="contain"
                />
              </div>
              <div class="book-des">
                <div class="book-name">
                  <div :title="scope.row.book.bookName" class="book-overflow">{{ scope.row.book.bookName }}</div>
                </div>
                <div class="book-author">
                  <div :title="scope.row.book.author" class="book-overflow">{{ scope.row.book.author }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="book.price" width="100px" />
        <el-table-column label="数量" align="center" width="250px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.num"
              size="mini"
              :min="1"
              :max="3"
              @change="handleChangeNum(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center">
          <template slot-scope="scope">
            <span
              style="color: #f40"
            >￥{{ (scope.row.num * scope.row.book.price) | num2Point }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
            <!-- <el-button size="mini" type="primary" @click="handleBuy(scope.$index, scope.row)">购买</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { delCartByIds } from '@/api/cart'

export default {

  data() {
    return {
      loading: false,
      multipleSelection: '',
      // 购买的商品种数
      buyCount: '',
      totalMoney: 0,
      // 购物车选中的商品id
      selectionId: []

    }
  },
  computed: {
    userCart() {
      return this.$store.getters.userCart
    }

  },
  created() {
    this.buyCount = 0
    this.totalMoney = 0
  },
  methods: {
    // 当点击购物车的多选框时触发
    handleSelectionChange(val) {
      // this.multipleSelection = val
      // console.log(val)
      if (val) {
        this.buyCount = val.length
        this.totalMoney = 0
        this.selectionId = []
        val.forEach(element => {
          element.selected = 1
          this.totalMoney += element.book.price * element.num
          this.selectionId.push(element.id)
        })
      } else {
        this.buyCount = 0
        this.totalMoney = 0
        this.selectionId = []
      }
    },
    // 从购物车删除某一个商品
    handleDelete(index, obj) {
      // console.log(obj)
      // this.userCart.splice(index, 1)
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const arr = []
        arr.push(obj.id)
        const idsObj = {
          ids: arr
        }
        delCartByIds(idsObj).then(res => {
          // 删除购物车成功，清除本地数据
          let tempCart = this.$store.getters.userCart
          tempCart = tempCart.filter(element => {
            return element.id !== obj.id
          })
          this.$store.commit('cart/SET_USERCART', tempCart)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {

        })
      })
    },
    // 修改商品的购买数量,并且生成总金额
    handleChangeNum(index, obj) {
      // console.log(index)
      obj.totalMoney = obj.num * obj.price
      this.totalMoney = 0
      this.userCart.forEach(element => {
        if (element.selected === 1) {
          this.totalMoney += element.book.price * element.num
        }
      })
    },

    // 删除已选择的商品
    deleteSelection() {
      if (this.selectionId.length === 0) {
        this.$message.error('请选择商品')
      } else {
        // this.$message.error('删除成功')
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          // 获取ids
          const idsObj = {
            ids: this.selectionId
          }
          delCartByIds(idsObj).then(res => {
            // 删除购物车成功，清除本地数据
            let tempCart = this.$store.getters.userCart
            tempCart = tempCart.filter(element => {
              // return element.id !== obj.id
              return !idsObj.ids.includes(element.id)
            })
            this.$store.commit('cart/SET_USERCART', tempCart)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success'
            })
          }).catch(() => {

          })
        })
      }
      // console.log(this.selectionId)
    },

    // 结算
    buyGoodList() {
      // this.$message.success('购买选中商品成功')
      // 等待生成订单，然后跳转到支付页面

      const arr = this.userCart.filter(element => {
        return this.selectionId.includes(element.id)
      })
      // console.log(arr)
      // 把即将购买的商品放在user.buyUserCart
      // this.$store.commit('cart/SET_BUYUSERCART', arr)
      localStorage.setItem('buyUserCart', JSON.stringify(arr))

      this.$router.push('/pay')

      // 遍历购物车所有商品，把数据回复原样
      this.setDefault()
    },
    setDefault() {
      const arr = this.$store.getters.userCart
      arr.forEach(element => {
        element.selected = 0
      })
      this.$store.commit('cart/SET_USERCART', arr)
    }
  }
}
</script>
<style lang="scss" scoped>
.header-div {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  .buy-div {
    display: flex;
    align-items: center;
    .choose,
    .total-money {
      margin-right: 40px;
    }
  }
}
.book-img-des-container {
  display: flex;
  .book-img {
    flex: 2;
    // width: 100px;
    height: 100px;
  }
  .book-des {
    flex: 3;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    // .book-name, .book-author{
    //   overflow: hidden;
    //   white-space: nowrap;
    //   text-overflow: ellipsis;
    // }
    // .book-overflow{
    //   overflow: hidden;
    //   white-space: nowrap;
    //   text-overflow: ellipsis;
    // }
  }

}

.table-div {
  margin-bottom: 40px;
  // text-align: center;
}
</style>
